package gruppoE;

import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


public class LettoreXML {
	
	private ArrayList<Log> logs; 
	
	public LettoreXML(String s, ArrayList<Log> logs){

		this.logs = logs;		
		
		DocumentBuilderFactory factory;
		DocumentBuilder builder;
		Document document;
		try {
		    factory = DocumentBuilderFactory.newInstance();
		    builder = factory.newDocumentBuilder();
		    document = builder.parse(new java.io.File(s));
		    System.err.println(document.getBaseURI());
		    gestioneDocumento(document,logs); 
		} catch(Exception ex) {
		    ex.printStackTrace();

		}
	}

	private void gestioneDocumento(Document document, ArrayList<Log> logs) {

		NodeList registro = document.getElementsByTagName("log");
		for(int i = 0; i < registro.getLength(); i++) {
			Element libro = (Element)registro.item(i);
				String luogo = libro.getElementsByTagName("luogo").item(0).getTextContent();
				String azione = libro.getElementsByTagName("azione").item(0).getTextContent();
				String operatore = libro.getElementsByTagName("operatore").item(0).getTextContent();
				NodeList stock = libro.getElementsByTagName("stocks");
//				NodeList stock = libro.getElementsByTagName("stocks").item(0).getChildNodes();

				logs.add(new Log(luogo,azione,operatore));
				System.out.println(logs);
				
					for (int j = 0; j < stock.getLength(); j++) {
						Element stocks = (Element)stock.item(i);
						String quant = "1";					//TOFIX
						String modello = stocks.getElementsByTagName("stock").item(0).getTextContent();
						logs.get(i).add(modello, Integer.parseInt(quant));
					}
					
				
		}
		System.err.println(logs.size()+" "+registro.getLength());
	}


}
